package org.example.controller;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;
import org.example.pojo.Product;
import org.example.service.ProductService;

import java.io.IOException;

@WebServlet("/products")
public class ProductServlet extends HttpServlet {
    private final ProductService productService = new ProductService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        HttpSession session = request.getSession(false); // 获取当前会话（不创建新会话）
        if (session == null || session.getAttribute("user") == null) {
            response.sendRedirect(request.getContextPath() + "/login.jsp");
            return;
        }

        String action = request.getParameter("action");

        if ("add".equals(action)) {
            request.getRequestDispatcher("addProduct.jsp").forward(request, response); // 跳转到添加商品页面
        } else if ("edit".equals(action)) {
            // 获取商品 ID
            int productId = Integer.parseInt(request.getParameter("productId"));
            Product product = productService.getProductById(productId);
            // 将商品信息传递到 JSP 页面
            request.setAttribute("product", product);
            request.getRequestDispatcher("editProduct.jsp").forward(request, response); // 跳转到编辑商品页面
        } else {
            request.setAttribute("productList", productService.getAllProducts());
            request.getRequestDispatcher("products.jsp").forward(request, response); // 返回商品列表页面
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");

        HttpSession session = request.getSession(false); // 获取当前会话（不创建新会话）
        if (session == null || session.getAttribute("user") == null) {
            response.sendRedirect(request.getContextPath() + "/login.jsp");
            return;
        }

        String action = request.getParameter("action");

        if ("delete".equals(action)) {
            handleDelete(request, response);
        } else if ("add".equals(action)) {
            handleAdd(request, response);
        } else if ("update".equals(action)) {
            handleUpdate(request, response);
        } else if ("order".equals(action)) {
            handleOrder(request, response, session);
        } else if ("deleteOrder".equals(action)) {
            handleDeleteOrder(request, response);
        }
    }

    private void handleDelete(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            int productId = Integer.parseInt(request.getParameter("productId"));
            boolean isDeleted = productService.deleteProduct(productId);
            if (isDeleted) {
                request.setAttribute("message", "商品删除成功！");
            } else {
                request.setAttribute("error", "商品删除失败，可能存在相关订单！");
            }
        } catch (Exception e) {
            request.setAttribute("error", "删除商品时发生错误！");
            e.printStackTrace();
        }
        response.sendRedirect("products");
    }

    private void handleAdd(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            String name = request.getParameter("name");
            double price = Double.parseDouble(request.getParameter("price"));
            int stock = Integer.parseInt(request.getParameter("stock"));

            productService.addProduct(new Product(name, price, stock));
            request.setAttribute("message", "商品添加成功！");
        } catch (Exception e) {
            request.setAttribute("error", "添加商品时发生错误！");
            e.printStackTrace();
        }
        response.sendRedirect("products");
    }

    private void handleUpdate(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            int productId = Integer.parseInt(request.getParameter("id"));
            String name = request.getParameter("name");
            double price = Double.parseDouble(request.getParameter("price"));
            int stock = Integer.parseInt(request.getParameter("stock"));

            productService.updateProduct(productId, name, price, stock);
            request.setAttribute("message", "商品更新成功！");
        } catch (Exception e) {
            request.setAttribute("error", "更新商品时发生错误！");
            e.printStackTrace();
        }
        response.sendRedirect("products");
    }

    private void handleOrder(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IOException {
        try {
            int productId = Integer.parseInt(request.getParameter("productId"));
            int quantity = Integer.parseInt(request.getParameter("quantity"));

            Object userObj = session.getAttribute("user");
            if (userObj == null) {
                response.sendRedirect(request.getContextPath() + "/login.jsp");
                return;
            }

            int userId = ((org.example.pojo.User) userObj).getId();

            boolean isOrdered = productService.placeOrder(userId, productId, quantity);

            if (isOrdered) {
                request.setAttribute("message", "下单成功！");
            } else {
                request.setAttribute("error", "下单失败，库存不足或商品不存在！");
            }
        } catch (Exception e) {
            request.setAttribute("error", "下单时发生错误：" + e.getMessage());
            e.printStackTrace();
        }
        response.sendRedirect("products");
    }

    private void handleDeleteOrder(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            int orderId = Integer.parseInt(request.getParameter("orderId"));

            boolean isRestored = productService.restoreStockByOrder(orderId);

            if (isRestored) {
                request.setAttribute("message", "订单删除成功，并已恢复库存！");
            } else {
                request.setAttribute("error", "订单删除失败！");
            }
        } catch (Exception e) {
            request.setAttribute("error", "删除订单时发生错误：" + e.getMessage());
            e.printStackTrace();
        }
        response.sendRedirect("orders");
    }
}
